package user.Controller.borrowBookRecord;

import com.alibaba.fastjson.JSONObject;
import user.Model.entity.record;
import user.Model.service.Service;
import user.utils.DBUitls;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
/*
* 获取借书文档里边的历史记录
* */
@WebServlet(name = "borrowBookRecordServlet",urlPatterns = "/user/borrowBookRecordServlet")
public class borrowBookRecordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ArrayList<record> records = new ArrayList<>();
        try {
            records = Service.getBorrowBookRecord();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                DBUitls.freeConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //向前端传输数据
        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();
        if (records.isEmpty()){
            object.put("code","-1");
            object.put("message","无法获取借阅记录");
            out.println(object);
        }
        else {
            object.put("code","200");
            object.put("message","获取借阅记录成功");
            object.put("userType","user");
            String recordList = JSONObject.toJSONString(records);
            object.put("records",recordList);
            out.println(object);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
